package com.skyline.energy.jdbc.impl;

import org.apache.commons.lang.StringUtils;

/**
 * SQL查询信息
 * 
 * @author wuqh
 * 
 */
public class SqlThreadLocal {
	private final SqlType sqlType;

	private final String sql;

	private final String shardKey;

	private SqlThreadLocal(String sql, String shardKey) {
		this.sql = sql;
		this.shardKey = shardKey;

		if (StringUtils.startsWithIgnoreCase(sql, "insert")) {
			this.sqlType = SqlType.INSERT;
		} else if (StringUtils.startsWithIgnoreCase(sql, "update")) {
			this.sqlType = SqlType.UPDATE;
		} else {
			this.sqlType = SqlType.QUERY;
		}
	}

	private static final ThreadLocal<SqlThreadLocal> locals = new ThreadLocal<SqlThreadLocal>();

	public static SqlThreadLocal get() {
		return locals.get();
	}

	public static SqlThreadLocal set(String sql, String shardKey) {
		SqlThreadLocal local = new SqlThreadLocal(sql, shardKey);
		locals.set(local);
		return local;
	}

	public static void remove() {
		locals.remove();
	}

	public SqlType getSqlType() {
		return sqlType;
	}

	public boolean isReadType() {
		return this.sqlType == SqlType.QUERY;
	}

	public boolean isWriteType() {
		return (this.sqlType == SqlType.UPDATE || this.sqlType == SqlType.INSERT);
	}

	public boolean isQueryType() {
		return isReadType();
	}

	public boolean isUpdateType() {
		return this.sqlType == SqlType.UPDATE;
	}

	public boolean isInsertType() {
		return this.sqlType == SqlType.INSERT;
	}

	public String getSql() {
		return sql;
	}

	public String getShardKey() {
		return shardKey;
	}
}
